package com.ophelisis.common.core;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.ophelisis.common.consts.ConstCode;
import com.ophelisis.common.util.UploadUtil;
import com.oreilly.servlet.multipart.FileRenamePolicy;

public class AlmapFileRenamePolicy implements FileRenamePolicy {
	public File rename(File fileObj) {
		long currentTime = System.currentTimeMillis();
		SimpleDateFormat simDf = new SimpleDateFormat("yyyyMMddHHmmss");
		int randomNumber = (int) (Math.random() * 100000);

		String uniqueFileName = "" + randomNumber + simDf.format(new Date(currentTime));
		
		String name = fileObj.getName();
		UploadUtil.setOldFileName(name);
		
		@SuppressWarnings("unused")
		String body = null;
		String ext = null;

		int dot = name.lastIndexOf(".");
		if (dot != -1) {
			body = name.substring(0, dot);
			ext = name.substring(dot); // includes "."
		} else {
			body = name;
			ext = "";
		}

		String tempName = uniqueFileName + ext;
		UploadUtil.setNewFileName(tempName);
		UploadUtil.setThumbnailFileName(ConstCode.thumbnailPrefix + tempName);
		
		fileObj = new File(fileObj.getParent(), tempName);

		if (createNewFile(fileObj)) {
			return fileObj;
		}

		int count = 0;
		while (!createNewFile(fileObj) && count < 9999) {
			count++;
			String newName = uniqueFileName + "_" + count + ext;
			fileObj = new File(fileObj.getParent(), newName);
		}
		
		return fileObj;
	}

	private boolean createNewFile(File fileObj) {
		try {
			return fileObj.createNewFile();
		} catch (IOException ignored) {
			return false;
		}
	}
}